package com.ziyun.erp.web.api.goods;

import java.util.*;

import com.utility.New;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.goods.TwbVo.TwbEditPriceVo;
import com.ziyun.erp.modules.goods.TwbVo.TwbGoodsVo;
import com.ziyun.erp.modules.goods.TwbVo.TwbStateCollectVo;
import com.ziyun.erp.modules.goods.VO.FastPriceVo;
import com.ziyun.erp.modules.goods.VO.PrintPriceVo;
import com.ziyun.erp.modules.goods.VO.VerifyPriceVo;
import com.ziyun.erp.modules.goods.entity.QuoteVO;
import com.ziyun.erp.modules.goodsCategory.entity.GoodsCategoryEntity;
import com.ziyun.erp.modules.quoteProduct.service.QuoteProductBaseInfoService;
import com.ziyun.erp.modules.supp.entity.SellerInfoEntity;
import com.ziyun.erp.modules.supp.service.SellerInfoService;
import io.renren.common.exception.RRException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.subject.ExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.utility.JsonUtils;
import com.ziyun.erp.modules.freightages.service.FreightTemplateService;
import com.ziyun.erp.modules.goods.entity.GoodsEntity;
import com.ziyun.erp.modules.goods.entity.GoodsProductEntity;
import com.ziyun.erp.modules.goods.service.GoodsAttributeService;
import com.ziyun.erp.modules.goods.service.GoodsBrandService;
import com.ziyun.erp.modules.goods.service.GoodsProductService;
import com.ziyun.erp.modules.goods.service.GoodsService;
import com.ziyun.erp.modules.goods.service.GoodsTemplateService;
import com.ziyun.erp.modules.goodsCategory.service.GoodsCategoryService;
import com.ziyun.erp.modules.goodsImage.entity.GoodsImageEntity;
import com.ziyun.erp.modules.goodsImage.service.GoodsImageService;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import io.renren.common.validator.ValidatorUtils;

/**
 * 商品表
 *
 * @author
 * @email
 * @date 2018-08-21 08:46:29
 */
@RestController
@RequestMapping("port/goods/goods")
public class GoodsControllerApi {
	@Autowired
	private GoodsService goodsService;

	@Autowired
	private GoodsProductService goodsProductService;

	@Autowired
	private GoodsAttributeService goodsAttributeService;

	@Autowired
	private QuoteProductBaseInfoService quoteProductBaseInfoService;

	@Autowired
	private GoodsCategoryService goodsCategoryService;

	@Autowired
	private SellerInfoService sellerInfoService;

	/**
	 * 列表
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/list")
	// public R list( @RequestParam Map<String, Object> params){
	public R list(@RequestBody Map paramBodyMap) {
		// goodsService.queryGoodsPage(page,params);
		Map params = (Map) paramBodyMap.get("params");
		PageUtils page = goodsService.queryPage(params);
		return R.ok().put("page", page);
	}

	/**
	 * 信息
	 */
	@RequestMapping("/info")
	public R info(@RequestBody Map paramBodyMap) {
		Integer goodsIdParam = (Integer) paramBodyMap.get("goodsId");
		Long goodsId = goodsIdParam.longValue();
		Integer sellerId = (Integer)paramBodyMap.get("sellerId");
//		GoodsEntity goodsProperty = goodsService.getAllGoodsProperty(goodsId);
//		// GoodsEntity goods = goodsService.selectById(goodsId);
//		HashMap<String, Object> map = new HashMap<>();
//		map.put("goods_id", goodsId);
//		map.put("disabled", 0);
//		// 获得并处理产品数据
//		List<GoodsProductEntity> goodsProductList = getAndHandlerProducts(goodsProperty, map);
//		if (goodsProductList.size() > 0) {
//			goodsProductService.setCraftValues(goodsProperty, goodsProductList.get(0));
//		}
//		// 关联设计服务
//		GoodsEntity designGood = null;
//		if (StringUtils.isNotBlank(goodsProperty.getRelateDesignIds())) {
//			designGood = goodsService.selectById(goodsProperty.getRelateDesignIds());
//		}
//		// //默认图片和详细图片处理返回
//		List<GoodsImageEntity> imageList = null;
//		if (StringUtils.isNotBlank(goodsProperty.getImageUrls())) {
//			imageList = goodsImageService.selectImageEntity(goodsProperty.getImageUrls());
//		}
//		List<GoodsImageEntity> infoList = null;
//		if (StringUtils.isNotBlank(goodsProperty.getInfoUrls())) {
//			infoList = goodsImageService.selectImageEntity(goodsProperty.getInfoUrls());
//		}
//		GoodsImageEntity videoEntity = null;
//		if (StringUtils.isNotBlank(goodsProperty.getVideoUrl())) {
//			videoEntity = goodsImageService.selectById(goodsProperty.getVideoUrl());
//		}
		return goodsService.getAllGoodsProperty(goodsId,sellerId);
	}

	/**
	 * 按map获得并处理products数据
	 * 
	 * @param goodsProperty
	 * @param map
	 * @return
	 */
	private List<GoodsProductEntity> getAndHandlerProducts(GoodsEntity goodsProperty, HashMap<String, Object> map) {
		List<GoodsProductEntity> goodsProductList = goodsProductService.selectByMap(map);
		if (goodsProductList.size() > 0) {
			String craftOptionIds = goodsProductList.get(0).getCraftOptionIds();
			String optionIds = goodsProductList.get(0).getOptionIds();
			String attributeNames = goodsAttributeService.getAttributeNamesByOptionIds(optionIds);
			String craftNames = goodsAttributeService.getCraftNamesByCraftOptionIds(craftOptionIds);
			goodsProperty.setAttributeNames(attributeNames);
			goodsProperty.setCraftNames(craftNames);
		}
		// 设置goodsProductList,将option对象赋值进入goodsProduct
		goodsProductService.setOptionByGoodsProductList(goodsProductList);
		// goodsProductService.setCraftOptionByGoodsProductList(goodsProductList);
		// 方案二
		return goodsProductList;
	}

	/**
	 * 保存-->方法弃置
	 */
	@RequestMapping("/save")
	// public R save(@RequestBody GoodsEntity goods){
	public R save(@RequestBody Map paramBodyMap) {
		GoodsEntity goods = (GoodsEntity) paramBodyMap.get("goods");
		goodsService.insert(goods);

		return R.ok();
	}

	/**
	 * 修改--编辑商品保存
	 */
	@RequestMapping("/update")
	// public R update(@RequestBody GoodsEntity goods){
	public R update(@RequestBody Map paramBodyMap) {
		Map params = (Map) paramBodyMap.get("params");
		String goodsStr = JsonUtils.object2String(params.get("goods"));
		GoodsEntity goods = JsonUtils.string2Object(goodsStr, GoodsEntity.class);
		Long userId = Long.valueOf(String.valueOf(params.get("userId")));
		goodsService.updateGoods(goods,userId);// 全部更新
//		if(goods.getExamineStatus().intValue() == 1){
			goodsService.loadGoodsCacheEvent(goods.getGoodsId());
//		}
		return R.ok();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	// public R delete(@RequestBody Long[] goodsIds){
	public R delete(@RequestBody Map paramBodyMap) {
		Long[] goodsIds = (Long[]) paramBodyMap.get("goodsIds");
		goodsService.deleteBatchIds(Arrays.asList(goodsIds));
		return R.ok();
	}

	/**
	 * 查询设计服务商品
	 */
	@RequestMapping("/designList")
	public R designList(@RequestBody Map paramBodyMap) {
		Map params = (Map) paramBodyMap.get("params");
//		PageUtils page = goodsService.queryPageNew(params);
		//为什么又改回第一种了
//		Map<String, Object> map = New.hashMap();
//		//注,这里的1964是设计服务分类的顶级分类id
//		map.put("parent_category_id",1964);
//		map.put("disabled",0);
//		List<GoodsCategoryEntity> goodsCategoryEntities = goodsCategoryService.selectByMap(map);
		PageUtils page = goodsService.queryPageNew(params);
		return R.ok().put("page", page);
	}

	/**
	 * 商品关联设计服务
	 */
	@RequestMapping("/addDesign")
	public R addDesign(@RequestBody Map paramBodyMap) {
		// @PathVariable("goodId")String goodId,@PathVariable("designId")String designId
		Integer nGoodId = StringUtil.getRequestParamInteger(paramBodyMap.get("goodId"));
		Integer nGesignId = StringUtil.getRequestParamInteger(paramBodyMap.get("designId"));
		goodsService.addDesign(nGoodId, nGesignId);
		return R.ok();
	}

	/**
	 * 信息
	 */
	@RequestMapping("/designInfo")
	public R designInfo(@RequestBody Map paramBodyMap) {
		// @PathVariable("designId") Long designId
		Map params = (Map) paramBodyMap.get("params");
		Integer designId = Integer.parseInt(params.get("designId").toString());
		GoodsEntity designGood = goodsService
				.selectById(designId);
		return R.ok().put("designGood", designGood);
	}

	/**
	 * 发布商品
	 */
	/**
	 * 保存
	 */
	@RequestMapping("/pushGood")
	// public R pushGood(@RequestBody GoodsEntity goods){
	public R pushGood(@RequestBody Map paramBodyMap) {
		Map params = (Map) paramBodyMap.get("params");
		String goodsStr = JsonUtils.object2String(params.get("goods"));
		GoodsEntity goods = JsonUtils.string2Object(goodsStr, GoodsEntity.class);
//		String goodsStr = (String) paramBodyMap.get("goods");
//		GoodsEntity goods = JSON.parseObject(goodsStr, new TypeReference<GoodsEntity>() {
//		});
		Integer sellerId = goods.getSellerId();
		SellerInfoEntity sellerInfoEntity = sellerInfoService.selectById(sellerId);
		List<SellerInfoEntity> sellerInfoEntities = null;
		if(sellerInfoEntity.getMainSellerId() == sellerId){
			Map<String, Object> map = New.hashMap();
			map.put("disabled",0);
			map.put("main_seller_id",sellerInfoEntity.getMainSellerId());
			sellerInfoEntities = sellerInfoService.selectByMap(map);
		}
		if(sellerInfoEntities != null && sellerInfoEntities.size() >0){
			goodsService.pushChainGoods(goods,sellerInfoEntities);
			goodsService.loadGoodsCacheEvent(goods.getGoodsId());
		}else{
			goodsService.pushGood(goods);
			goodsService.loadGoodsCacheEvent(goods.getGoodsId());
		}

		return R.ok();
	}

	/**
	 * updateStatus更新spu状态
	 */
	@RequestMapping("/updateStatus")
	public R updateStatus(@RequestBody Map paramBodyMap) {
		Map params = (Map) paramBodyMap.get("params");
		Long userId = Long.valueOf(String.valueOf(params.get("userId")));
		Long goodsId = Long.valueOf(String.valueOf(params.get("goodsId")));
		String status = (String) params.get("status");
		goodsService.updateStatus(goodsId, status,userId);
		goodsService.loadGoodsCacheEvent(goodsId);
		return R.ok();
	}


	/**
	 * 根据分类获得所有模板表数据
	 */
	@RequestMapping("/quoteTemplate")
	public R getQuoteTemplate(@RequestBody Map paramBodyMap) {
//	public R getQuoteTemplate(@PathVariable("categoryId") String categoryId){
		Map params = (Map) paramBodyMap.get("params");
		Integer categoryId = Integer.parseInt(params.get("categoryId").toString());
		Integer factoryId = Integer.parseInt(params.get("factoryId").toString());
		List<Map> allQuoteTemplate = quoteProductBaseInfoService.getAllQuoteTemplate(categoryId,factoryId);

		return R.ok().put("allQuoteTemplate",allQuoteTemplate);

	}

	/**
	 * 发布商品
	 */
	@RequestMapping("/pushQuoteGood")
	public R pushQuoteGood(@RequestBody Map paramBodyMap){// QuoteVO quoteVO
		Map params = (Map) paramBodyMap.get("params");
		String quoteVO = JsonUtils.object2String(params.get("quoteVO"));
		QuoteVO quoteVO1 = JsonUtils.string2Object(quoteVO, QuoteVO.class);

		Integer sellerId = quoteVO1.getGoodsEntity().getSellerId();
		SellerInfoEntity sellerInfoEntity = sellerInfoService.selectById(sellerId);
		List<SellerInfoEntity> sellerInfoEntities = null;
		if(sellerInfoEntity.getMainSellerId() == sellerId){
			Map<String, Object> map = New.hashMap();
			map.put("disabled",0);
			map.put("main_seller_id",sellerInfoEntity.getMainSellerId());
			sellerInfoEntities = sellerInfoService.selectByMap(map);
		}
		if(sellerInfoEntities != null && sellerInfoEntities.size() > 0){
			goodsService.pushChainQuoteGood(quoteVO1,sellerInfoEntities);
			goodsService.loadGoodsCacheEvent(quoteVO1.getGoodsEntity().getGoodsId());
		}else{
			goodsService.pushQuoteGood(quoteVO1);
			goodsService.loadGoodsCacheEvent(quoteVO1.getGoodsEntity().getGoodsId());
		}

		return R.ok();
	}

	/**
	 *工艺校验价格
	 */
	@RequestMapping("/verifyCraftPrice")
	public R verifyCraftPrice(@RequestBody Map paramBodyMap){
		Map params = (Map) paramBodyMap.get("params");
//        System.out.println(verifyPriceVo);
		String verifyPriceVo = JsonUtils.object2String(params.get("verifyPriceVo"));
		Long sellerId = Long.valueOf(String.valueOf(params.get("sellerId")));
		VerifyPriceVo verifyPriceVo1 = JsonUtils.string2Object(verifyPriceVo, VerifyPriceVo.class);
		//先做一下权限校验
		String result = goodsService.verifyCraftPrice(verifyPriceVo1,sellerId);
		return R.ok().put("result",result);
	}

	/**
	 *工艺校验价格
	 */
	@RequestMapping("/quotePrice")
	public R quotePrice(@RequestBody Map paramBodyMap){
//        System.out.println(ids);
		//先做一下权限校验
//        String result = goodsService.verifyCraftPrice(verifyPriceVo);
		Map params = (Map) paramBodyMap.get("params");
		String ids = (String) params.get("ids");
		int sellerId = Integer.parseInt(String.valueOf(params.get("sellerId")));
//		Integer sellerId = Integer.parseInt((String)params.get("sellerId"));
		String result = goodsService.quotePrice(ids,sellerId);
		return R.ok().put("result",result);
	}

	/**
	 *商务印刷机器校验
	 */
	@RequestMapping("/verifyPrintPrice")
	public R verifyPrintPrice(@RequestBody Map paramBodyMap){//PrintPriceVo printPriceVo
		Map params = (Map) paramBodyMap.get("params");
		String printPriceVo = JsonUtils.object2String(params.get("printPriceVo"));
		Integer factoryId = Integer.parseInt(String.valueOf(params.get("factoryId")));
		PrintPriceVo printPriceVo1 = JsonUtils.string2Object(printPriceVo, PrintPriceVo.class);
		String result = goodsService.verifyPrintPrice(printPriceVo1,factoryId);
		return R.ok().put("result",result);
	}

	/**
	 * 数码快印组合商品计价校验
	 */
	@RequestMapping("/verifyFastPrice")
	public R verifyFastPrice(@RequestBody Map paramBodyMap){//List<FastPriceVo> fastPriceVoList
		Map params = (Map) paramBodyMap.get("params");
		Long sellerId = Long.valueOf(String.valueOf(params.get("sellerId")));
		String fastPriceVoList = JsonUtils.object2String(params.get("fastPriceVoList"));
		List<FastPriceVo> fastPriceVoList1 = JsonUtils.string2Collection(fastPriceVoList, List.class, FastPriceVo.class);
		String result = goodsService.verifyFastPrice(fastPriceVoList1,sellerId.intValue());
		return R.ok().put("result",result);
	}


	/**
	 * 发布商品
	 */
	@RequestMapping("/updateQuoteGood")
	public R updateQuoteGood(@RequestBody Map paramBodyMap ){//QuoteVO quoteVO
		Map params = (Map) paramBodyMap.get("params");
		String quoteVO1 = JsonUtils.object2String(params.get("quoteVO"));
		QuoteVO quoteVO = JsonUtils.string2Object(quoteVO1, QuoteVO.class);
		Integer sellerId = Integer.parseInt((String.valueOf(params.get("sellerId"))));
		String username = (String) params.get("username");
		quoteVO.getGoodsEntity().setSellerId(sellerId);
//        quoteVO.getGoodsEntity().setCreateName(UserUtils.getCurentUser().getUsername());
		for(int i = 0;i<quoteVO.getQuoteProductBaseInfoVOList().size();i++){
			quoteVO.getQuoteProductBaseInfoVOList().get(i).setUpdateUser(username);
			quoteVO.getQuoteProductBaseInfoVOList().get(i).setUpdateDate(new Date());
			quoteVO.getQuoteProductBaseInfoVOList().get(i).setCreateUser(quoteVO.getGoodsEntity().getCreateName());
		}
		goodsService.editQuoteGood(quoteVO);
		//判断审核状态确定是否需要抛事件
//		if(quoteVO.getGoodsEntity().getExamineStatus().intValue() == 1){
			goodsService.loadGoodsCacheEvent(quoteVO.getGoodsEntity().getGoodsId());
//		}
		return R.ok();
	}

	/**
	 * 改变商品审核状态
	 */
	@RequestMapping("/examineGoods")
	public R examineGoods(@RequestBody Map paramBodyMap){
		Map params = (Map) paramBodyMap.get("params");
		Integer goodsId = Integer.parseInt(String.valueOf(params.get("goodsId")));
		Integer examine = Integer.parseInt(String.valueOf(params.get("examine")));
		//判断examine是否为0,如果examine不为0则数据出错
		if(examine.intValue() != 0){
			return R.error("商品状态重置异常,请联系管理员!");
		}
		goodsService.examineGoods(goodsId,examine);

		return R.ok();
	}

	/**
	 * twb发布商品第二部,根据spus获得商品信息
	 */
	@RequestMapping("/getGoodsByGoodsIds")
	public R getGoodsByGoodsIds(@RequestBody Map paramBodyMap){
		Map params = (Map) paramBodyMap.get("params");
		List<Integer> goodsIds = (List<Integer>) params.get("goodsIds");
		Integer freightId = (Integer) params.get("freightId");
		return goodsService.getTwbGoodsVoList(goodsIds,freightId);
	}

    /**
     * twb发布商品第二部,根据spu获得商品信息
     */
    @RequestMapping("/getTwbGoodsInfo")
    public R getTwbGoodsInfo(@RequestBody Map paramBodyMap){
        Map params = (Map) paramBodyMap.get("params");
        Long goodsId = Long.valueOf(String.valueOf(params.get("goodsId")));
        return goodsService.getTwbGoodsVo(goodsId);
    }

	/**
	 * twb发布商品预加载数据,
	 */
	@RequestMapping("/getUnitLibrary")
	public R getUnitLibrary(@RequestBody Map paramBodyMap){
		Map params = (Map) paramBodyMap.get("params");
		return goodsService.getUnitLibrary();
	}

	/**
	/**
	 *图文宝批量发布商品
	 */
	@RequestMapping("/twbListPushGoods")
	public R twbListPushGoods(@RequestBody Map paramBodyMap){
		Map params = (Map) paramBodyMap.get("params");
		String twbGoodsVoList = JsonUtils.object2String(params.get("twbGoodsVoList"));
		List<TwbGoodsVo> list = JsonUtils.string2Collection(twbGoodsVoList, List.class, TwbGoodsVo.class);
		String userName = String.valueOf(params.get("userName"));
		Boolean pushMark = (Boolean) params.get("pushMark");
		Long sellerId = Long.valueOf(String.valueOf(params.get("sellerId")));
		if(pushMark){
			//商户商品发布
			goodsService.pushTwbGoodsVoListNewVersions(list,userName,sellerId);
		}else{
			//商户商品编辑
			goodsService.pushTwbGoodsVoList(list,userName);
		}
		//抛事件
        goodsService.twbGoodsEvent(list);
        return R.ok();
	}

	/**
	 * 信息
	 */
	@RequestMapping("/editTwbGoodsPrice")
	public R editTwbGoodsPrice(@RequestBody Map paramBodyMap){
		Map params = (Map) paramBodyMap.get("params");
		Long goodsId = Long.valueOf(String.valueOf(params.get("goodsId")));
		return goodsService.editTwbGoodsPrice(goodsId);
	}


	/**
	 *图文宝商品列表
	 */
	@RequestMapping("/getTwbGoodsList")
	public R getTwbGoodsList(@RequestBody Map paramBodyMap){
		Map params = (Map) paramBodyMap.get("params");
		return goodsService.getTwbGoodsList(params);
	}

	/**
	 *图文宝列表商品价格编辑修改保存
	 */
	@RequestMapping("/saveTwbEditPrice")
	public R saveTwbEditPrice(@RequestBody Map paramBodyMap){
		Map params = (Map) paramBodyMap.get("params");
		String twbEditPriceVoList = JsonUtils.object2String(params.get("twbEditPriceVoList"));
		List<TwbEditPriceVo> list = JsonUtils.string2Collection(twbEditPriceVoList, List.class, TwbEditPriceVo.class);
		return goodsService.saveTwbGoodsListPrice(list);
	}

	/**
	 *图文宝分类和商品获取
	 */
	@RequestMapping("/getTwbCateAndGoods")
	public R getTwbCateAndGoods(@RequestBody Map paramBodyMap){
		Map params = (Map) paramBodyMap.get("params");
		Long sellerId = Long.valueOf(String.valueOf(params.get("sellerId")));
		return goodsService.getTwbCateAndGoods(sellerId);
	}

	/**
	 *图文宝列表商品批量修改状态
	 */
	@RequestMapping("/twbListOperation")
	public R twbListOperation(@RequestBody Map paramBodyMap){
		Map params = (Map) paramBodyMap.get("params");
		System.out.println(JsonUtils.map2String(params));
		String goodIdList = JsonUtils.object2String(params.get("goodIdList"));
		List<Long> goodsIds = JsonUtils.string2Collection(goodIdList, List.class, Long.class);
		String marketable = (String) params.get("marketable");
		return goodsService.twbListOperation(goodsIds,marketable);
	}

	/**
	 *图文宝小程序列表商品批量修改状态
	 */
	@RequestMapping("/twbStateCollect")
	public R twbStateCollect(@RequestBody Map paramBodyMap){
		Map params = (Map) paramBodyMap.get("params");
		System.out.println(JsonUtils.map2String(params));

		return R.ok();
	}

    /**
     *图文宝小程序商户商品状态统计
     */
    @RequestMapping("/twbGoodsStateCount")
    public R twbGoodsStateCount(@RequestBody Map paramBodyMap){
        Map params = (Map) paramBodyMap.get("params");
        System.out.println(JsonUtils.map2String(params));
        Long sellerId = Long.valueOf(String.valueOf(params.get("sellerId")));
//        Long sellerId = (Long) params.get("sellerId");
        TwbStateCollectVo twbStateCollectVo =goodsService.getTwbGoodsStateCount(sellerId);
        return R.ok().put("twbStateCollectVo",twbStateCollectVo);
    }


}
